import TableV2, { TableV2Type } from "@/components/TableV2";
import { WorkArea } from "@/components/WorkArea";
import { Dialog } from "@/hoc/Diolog";
import { ToolsItemType } from "@/hooks/useElementFormItem";
import { useEmiter } from "@/hooks/useEmiter";
import { useTableV2 } from "@/hooks/useTableV2";
import apiStore from "@/stores/apiStore";
import { MenuItemType, UserListReturnType } from "@Tea/model";
import { debounce, isSuccessCode, useElMessageBox, useGloablLoading } from "@Tea/utils";
import { PropType, Ref, computed, defineComponent, onMounted, reactive, ref, watch } from "vue";
import classes from "./menuPower.module.scss"
import { httpCommonHandle } from "@/utils/httpUtils";

export const MenuPowerDialog = defineComponent({
  props: {
    visible: {
      type: Object as PropType<Ref<boolean>>,
      required: true,
    },
    // 当前用户
    curMember: {
      type: Object as PropType<Ref<UserListReturnType>>,
      required: true
    },
    // 这里可以通过props 也可以 用 emiter
    handleSuccess: Function,
    handleFail: Function,
  },
  setup(props, ctx) {

    const { tableName } = useEmiter("menuPowerDialog")
    const {
      tableLoading, setAllTreeExpand, setRowData,
      clearTreeExpand, getCheckboxRecords, setAllCheckboxRow,
      clearCheckboxRow
    } = useTableV2(tableName)
    const { getSystemMenu, getUserMenuIdById,chagneMemberMenu } = apiStore().api

    // table配置
    const table = ref<TableV2Type["tableConfig"]>({
      data: [],
      rowConfig: { keyField: "menuId" },
      treeConfig: {
        transform: true, rowField: 'menuId', parentField: 'pMenuId', expandRowKeys: [1]
      },
      checkboxConfig: { labelField: "code", highlight: true, checkRowKeys: [], checkStrictly: false}
    })

    // colmun 配置
    const colmun: TableV2Type["colmunConfig"] = [
      { field: "code", type: "checkbox", title: "菜单编码", treeNode: true },
      { field: "title", title: "菜单名称" },
      { field: "creator", title: "创建人", width: 100 },
      { field: "createTime", title: "创建时间", width: 200 },
    ]

    // 搜索条件
    const searchForm = reactive({
      enable: 1,
    })

    // 全选或者反选
    const isSelectAll = ref(true)
    // 全选或者反选的标识
    const selectFlag = computed(()=> isSelectAll.value ? '全部打开' :'全部关闭')

    // 搜索
    const searchData = async () => {
      try {
        tableLoading.value = true
        const promises = Promise.all([
          getSystemMenu(searchForm),
          getUserMenuIdById(props.curMember.value.userId)
        ])

        const [meunList, userMenuList] = await promises
        tableLoading.value = false

        if (isSuccessCode(meunList.code) && isSuccessCode(userMenuList.code)) {
          setRowData(meunList.data)
          table.value.checkboxConfig.checkRowKeys = userMenuList.data
        }

      } catch (e) {
        tableLoading.value = false
      }
    }

    // 打开或者关闭全部
    const closeOrOpenTree = () => {
      isSelectAll.value ? setAllTreeExpand() : clearTreeExpand()
      isSelectAll.value = !isSelectAll.value
    }

    // 确认修改
    const confirmEdit = () => {
      useElMessageBox({
        content: "确认后可以使用已选的菜单，未选择的菜单将不能使用，确定要继续吗？",
        thenCallback: () => {
          const selectRows = getCheckboxRecords<MenuItemType[]>()
          
          httpCommonHandle({
            loading: useGloablLoading,
            callBack: () => chagneMemberMenu({
              userId: props.curMember.value.userId,
              menuIds: selectRows.map(m => m.menuId)
            }),
            onSuccess: searchData
          })
        }
      })
    }

    // 创建工具的配置
    const toolsList: ToolsItemType<typeof searchForm>[] = [
      {
        type: "button", content: "确认修改", attr: {
          onClick: () => confirmEdit()
        }
      },
      {
        type: "button", content: selectFlag, attr: {
          onClick: () => closeOrOpenTree()
        }
      }
    ]

    onMounted(() => {
      searchData()
    })

    // 显示区域
    const Content = () => (
      <section class={`${classes.menuPower} m-padding m-fullBox m-window`}>
        <WorkArea
          tools={toolsList}
          onSearch={searchData}
          /
        >
        <TableV2
          v-loading={tableLoading.value}
          vexTableV2={{
            tableConfig: table.value,
            colmunConfig: colmun
          }}
          initPagination={false}
          tableName={tableName}
          /
        >
      </section>
    )
    
    return () => (
      Dialog({
        visible: props.visible,
        title: "成员菜单权限",
        width: "80%",
        content: Content,
        notUseFooter:true,
        onClose: () => {
          props.curMember.value = null
        }
      })
    )
  },
})